package cn.weixin.song.controller.wx;

import java.io.IOException;
import java.util.List;

import cn.weixin.song.interceptor.WeixinAccessInterceptor;
import cn.weixin.song.model.App;
import cn.weixin.song.model.CouponSn;
import cn.weixin.song.model.User;
import cn.weixin.song.util.QRCodeUtil;
import cn.weixin.song.util.WeixinUtils;

import com.github.sd4324530.fastweixin.api.response.GetSignatureResponse;
import com.jcbase.core.controller.JCBaseController;
import com.jcbase.core.view.InvokeResult;
import com.jfinal.aop.Before;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

/**
 * 优惠券
 * 
 * @author eason
 * 
 */
public class WxCouponController extends JCBaseController {

	@Before(WeixinAccessInterceptor.class)
	public void index() {
		String openid = this.getPara("openid");
		Integer appId = this.getParaToInt("appId");
		if (StrKit.isBlank(openid) || appId == null)
			return;
		User user = User.dao.getUser(appId, openid);
		App app = App.dao.findById(appId);
		if (user != null && app != null) {
			this.setAttr("user", user);
			this.setAttr("wxAppId", app.getWxAppId());
			GetSignatureResponse getSignatureResponse = WeixinUtils.getJsAPI(
					app.getWid()).getSignature(this.getThisUrl());
			this.setAttr("appData", getSignatureResponse);
			List<Record> r_list = CouponSn.dao.getMyUsedCouponSnList(user
					.getId());
			List<Record> l_list = CouponSn.dao.getMyNotUseCouponSnList(user
					.getId());
			this.setAttr("r_list", r_list);
			this.setAttr("l_list", l_list);
			this.setAttr("r_list_size", r_list.size());
			this.setAttr("l_list_size", l_list.size());
			this.render("my_coupons.jsp");
			return;
		}
	}

	public void qrcode() {
		String sn = this.getPara();
		if (StrKit.notBlank(sn)) {
			String content = PropKit.get("wx_base_url") + "coupon/check_view/"
					+ sn.trim();
			try {
				QRCodeUtil.encode(content, null, this.getResponse()
						.getOutputStream(), false, 200);
				this.renderNull();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 优惠券核销页面
	 */
	public void check_view() {
		String sn = this.getPara();
		if (StrKit.notBlank(sn)) {
			Record item = CouponSn.dao.findBySnCode(sn);
			this.setAttr("item", item);
			this.setAttr("check_pwd", this.getCheckPwd());
			this.render("coupon_check.jsp");
		}
	}

	/**
	 * 核销优惠券
	 */
	@Before(Tx.class)
	public void check() {
		String snCode = this.getPara("sn");
		String pwd = this.getPara("pwd");
		InvokeResult invokeResult = CouponSn.dao.consume(snCode, pwd);
		this.setCookie("check_pwd", pwd, 60 * 60 * 24 * 30);
		this.renderJson(invokeResult);
	}
    /**
     * 将核销密码保存到cookie，减少商家多次输入
     */
	protected void saveCheckPwd(String checkPwd) {
		this.setCookie("check_pwd", checkPwd, 60 * 60 * 24 * 30);
	}

	protected String getCheckPwd() {
		return this.getCookie("check_pwd");
	}
}
